//
//  MYGCaseFileSelectView.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/26.
//

import UIKit
import JXSegmentedView

class MYGCaseFileSelectView: UIView {
    var dataArr:[MYGCaseClasmListModel] = []
    var dismissBlock:(() -> ())?
    var nextBlock:((MYGCaseClasmListModel) -> ())?
    var selectBtn:UIButton!
    var typeInt:String = "outpatient"
    var moduleType:Int = 1
    var patientId:Int = 0{
        didSet{
            inniUI()
            getDatasource()
        }
    }
    var selectModel:MYGCaseClasmListModel = MYGCaseClasmListModel()
    override init(frame: CGRect) {
        super.init(frame: frame)

    }
    @objc func cancelAction(){
        if let c = dismissBlock {
            c()
        }
    }
    @objc func sureAction(){
        if let c = nextBlock {
            c(selectModel)
        }
    }
    @objc func changeAction(btn:UIButton){
        let arr = ["outpatient","inspection","medication","operation","examination"]
        selectBtn.isSelected = false
        btn.isSelected = true
        selectBtn = btn
        typeInt = arr[btn.tag - 1]
        getDatasource()
    }
    private func getDatasource(){
        MYGNetwork<MYGSurgicalApi, MYGPageModel<MYGCaseClasmListModel>>.request(target: .patientCaseList(params: [
            "patient_id":patientId,
            "key":typeInt,
            "type":moduleType])) {[self] item in
                dataArr = item.list
                casesDetailTable.reloadData()
            } failed: { _, error in
                MMYGHUD.showToast(text: error)
            }
    }
    private func inniUI(){
        self.backgroundColor = .rgba(0, 0, 0,0.6)
        addSubview(whiteBackView)
        whiteBackView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(17.5)
            make.right.equalToSuperview().offset(-17.5)
            make.top.equalToSuperview().offset(76)
            make.bottom.equalToSuperview().offset(-60)
        }
        whiteBackView.addSubview(titleLabel)
        titleLabel.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.top.equalToSuperview().offset(19)
            make.height.equalTo(24)
        }
        whiteBackView.addSubview(segmentedView)
        segmentedView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(10)
            make.top.equalTo(titleLabel.snp.bottom).offset(20)
            make.right.equalToSuperview().offset(-20)
            make.height.equalTo(45)
        }
        whiteBackView.addSubview(topView)
        topView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(segmentedView.snp.bottom).offset(14)
            make.height.equalTo(45)
        }
        whiteBackView.addSubview(casesDetailTable)
        casesDetailTable.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(topView.snp.bottom).offset(10)
            make.bottom.equalToSuperview().offset(-50)
        }
        whiteBackView.addSubview(cancelBtn)
        cancelBtn.snp.makeConstraints { make in
            make.left.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo((screenWidth - 35)/2)
        }
        whiteBackView.addSubview(sureBtn)
        sureBtn.snp.makeConstraints { make in
            make.right.equalToSuperview()
            make.bottom.equalToSuperview()
            make.height.equalTo(50)
            make.width.equalTo((screenWidth - 35)/2)
        }
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private lazy var whiteBackView:UIView = {
        let cont = UIView()
        cont.backgroundColor = .white
        cont.layerCornerRadius = 12
        return cont
    }()
    lazy var titleLabel: UILabel = {
        let cont = UILabel()
        cont.text = "选择病历"
        cont.font = .medium(16)
        cont.textColor = .rgba(44, 44, 44)
        return cont
    }()
    private lazy var segmentedView: JXSegmentedView = {
        let segmentedView = JXSegmentedView()
        segmentedView.delegate = self
        segmentedView.dataSource = dataSource
        let indicator = JXSegmentedIndicatorLineView()
        indicator.indicatorWidth = SCALEWIDTH(16)
        indicator.indicatorHeight = SCALEWIDTH(3)
        indicator.indicatorColor = .rgba(32, 92, 255, 1)
        segmentedView.indicators = [indicator]
        return segmentedView
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["按模块","按病历"]
        dataSource.titleNormalFont = .regular(13)
        dataSource.titleNormalColor = .rgba(118, 118, 118, 1)
        dataSource.titleSelectedFont = .regular(16)
        dataSource.titleSelectedColor = .rgba(32, 92, 255, 1)
        dataSource.isItemSpacingAverageEnabled = false
        return dataSource
    }()
    private lazy var topView:UIView = {
        let cont = UIView()
        cont.layer.masksToBounds = true
        var startX = 17.0
        var startY = 0.0
        var tagsArr = ["门诊","检验检查","用药记录","手术","体检"]
        for ind in 0...4{
            let btn = UIButton()
            btn.setTitle(tagsArr[ind], for: .normal)
            btn.setTitleColor(.rgba(51, 51, 51), for: .normal)
            btn.setTitleColor(.rgba(255, 255, 255), for: .selected)
            btn.setBackgroundColor(color: .rgba(240, 240, 240), forState: .normal)
            btn.setBackgroundColor(color: .rgba(85, 126, 237, 1), forState: .selected)
            btn.titleLabel?.font = .regular(12)
            btn.layerCornerRadius = 3
            btn.tag = ind + 1
            btn.addTarget(self, action: #selector(changeAction(btn:)), for: .touchUpInside)
            cont.addSubview(btn)
            btn.snp.makeConstraints { make in
                make.left.equalToSuperview().offset(startX)
                make.top.equalToSuperview().offset(startY)
                make.size.equalTo(CGSize(width: 55, height: 18.5))
            }
            if ind == 0 {
                btn.isSelected = true
                selectBtn = btn
            }
            if startX + 70 > screenWidth - 35{
                startX = 17
                startY = startY + 30
            }else{
                startX = startX + 70
            }
        }
        return cont
    }()
    private lazy var casesDetailTable: UITableView = {
        let cont = UITableView(frame: CGRectZero, style: .grouped)
        cont.delegate = self
        cont.dataSource = self
        cont.separatorStyle = .none
        cont.backgroundColor = .clear
        cont.showsVerticalScrollIndicator = false
        return cont
    }()
    private lazy var cancelBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("取消", for: .normal)
        vi.titleLabel?.font = .regular(17)
        vi.setTitleColor(.rgba(102, 102, 102), for: .normal)
        vi.addTarget(self, action: #selector(cancelAction), for: .touchUpInside)
        vi.layer.borderWidth = 0.5
        vi.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        return vi
    }()
    private lazy var sureBtn:UIButton = {
        let vi = UIButton()
        vi.setTitle("确认", for: .normal)
        vi.titleLabel?.font = .regular(17)
        vi.setTitleColor(.rgba(69, 131, 250, 1), for: .normal)
        vi.addTarget(self, action: #selector(sureAction), for: .touchUpInside)
        vi.layer.borderWidth = 0.5
        vi.layer.borderColor = RGBA(r: 212, g: 212, b: 212, a: 1).cgColor
        return vi
    }()
}
extension MYGCaseFileSelectView:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if moduleType == 1{
            let cell = MYGCaseFilesSelectCell(style: .default, reuseIdentifier: "MYGCaseFilesSelectCell")
            cell.selectionStyle = .none
            let tagsArr = ["门诊","检验检查","用药记录","手术","体检"]
            var model = dataArr[indexPath.row]
            model.module = tagsArr[selectBtn.tag - 1]
            cell.model = model
            if model.id == selectModel.id {
                cell.selectBtn.isSelected = true
            }else{
                cell.selectBtn.isSelected = false
            }
            return cell
        }else{
            let cell = MYGCaseFilesSelectCell(style: .default, reuseIdentifier: "MYGCaseFilesSelectCell")
            cell.selectionStyle = .none
            var model = dataArr[indexPath.row]
            cell.model = model
            if model.id == selectModel.id {
                cell.selectBtn.isSelected = true
            }else{
                cell.selectBtn.isSelected = false
            }
            return cell
        }
        
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        95
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        selectModel = dataArr[indexPath.row]
        casesDetailTable.reloadData()
    }
    
}

extension MYGCaseFileSelectView: JXSegmentedViewDelegate{
    //点击选中或者滚动选中都会调用该方法。适用于只关心选中事件，而不关心具体是点击还是滚动选中的情况。
    func segmentedView(_ segmentedView: JXSegmentedView, didSelectedItemAt index: Int) {
        moduleType = index + 1
        typeInt = ""
        topView.snp.updateConstraints { make in
            make.height.equalTo(index == 0 ? 45 : 0)
        }
        selectModel = MYGCaseClasmListModel()
        getDatasource()
    }
    // 点击选中的情况才会调用该方法
    func segmentedView(_ segmentedView: JXSegmentedView, didClickSelectedItemAt index: Int) {}
    // 滚动选中的情况才会调用该方法
    func segmentedView(_ segmentedView: JXSegmentedView, didScrollSelectedItemAt index: Int) {}
    // 正在滚动中的回调
    func segmentedView(_ segmentedView: JXSegmentedView, scrollingFrom leftIndex: Int, to rightIndex: Int, percent: CGFloat) {}
}
